<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon-wrapper bg-blue">
             <el-icon><User /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-text">用户总数</div>
            <div class="card-num">{{ stats.userCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon-wrapper bg-green">
            <el-icon><Goods /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-text">商品总数</div>
            <div class="card-num">{{ stats.productCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon-wrapper bg-orange">
            <el-icon><Tickets /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-text">订单总数</div>
            <div class="card-num">{{ stats.orderCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-icon-wrapper bg-red">
            <el-icon><Money /></el-icon>
          </div>
          <div class="card-content">
            <div class="card-text">总销售额</div>
            <div class="card-num">¥{{ stats.totalSales.toFixed(2) }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- Sales Trend Chart -->
    <el-row style="margin-top: 20px;">
        <el-col :span="24">
            <el-card shadow="never">
                <template #header>
                    <span>订单金额趋势</span>
                </template>
                <v-chart class="chart" :option="lineChartOption" autoresize />
            </el-card>
        </el-col>
    </el-row>

    <el-row class="chart-row">
      <el-col :span="24">
        <el-card shadow="never">
          <div id="category-tree-chart" style="height: 500px; width: 100%;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Bottom Card: Top Spender of the Day -->
    <el-row style="margin-top: 20px;">
        <el-col :span="24">
            <el-card shadow="never">
                <template #header>
                    <div class="card-header">
                        <span>今日消费冠军</span>
                    </div>
                </template>
                <div v-if="topSpenderData && topSpenderData.user" class="top-spender-content">
                    <el-descriptions :column="2" border>
                        <el-descriptions-item label="用户名">{{ topSpenderData.user.name }}</el-descriptions-item>
                        <el-descriptions-item label="今日总消费">
                            <el-tag type="danger" size="large">¥{{ topSpenderData.totalSpentToday.toFixed(1) }}</el-tag>
                        </el-descriptions-item>
                    </el-descriptions>
                    <h4 style="margin-top: 20px; margin-bottom: 10px;">今日订单列表</h4>
                    <el-table :data="topSpenderData.orders" stripe style="width: 100%">
                        <el-table-column label="商品" width="200">
                            <template #default="scope">{{ productsMap[scope.row.productId] || '未知商品' }}</template>
                        </el-table-column>
                        <el-table-column prop="totalAmount" label="订单金额">
                            <template #default="scope">¥{{ scope.row.totalAmount.toFixed(1) }}</template>
                        </el-table-column>
                        <el-table-column label="下单时间">
                            <template #default="scope">
                              {{ formatDateToCN(scope.row.orderDate) }}
                            </template>
                        </el-table-column>
                         <el-table-column prop="status" label="状态">
                            <template #default="scope">
                                <el-tag :type="scope.row.status === 'end' ? 'success' : 'warning'">{{ scope.row.status }}</el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <el-empty v-else description="今日暂无消费数据"></el-empty>
            </el-card>
        </el-col>
    </el-row>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import apiClient from '../../axios/axios';
import { ElMessage, ElIcon } from 'element-plus';
import { User, Goods, Tickets, Money } from '@element-plus/icons-vue';
import type { AxiosResponse } from 'axios';

// ECharts imports
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
} from 'echarts/components';
import VChart from 'vue-echarts';
import * as echarts from 'echarts';

// ECharts setup
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
]);

interface Order {
    id: number;
    customerId: number;
    productId: number;
    addressId: number;
    status: string;
    subtotalAmount: number;
    shippingFee: number;
    discountAmount: number;
    totalAmount: number;
    orderDate: string; // Assuming 'YYYY-MM-DD HH:MM:SS' format
}

interface Stats {
  userCount: number;
  productCount: number;
  orderCount: number;
  totalSales: number;
}

interface CategorySalesFlat {
  categoryId: number;
  categoryName: string;
  totalSales: number;
  parentCategoryId?: number | null;
}

interface CategoryTreeNode {
  name: string;
  value: number;
  children?: CategoryTreeNode[];
}

interface TopSpenderDto {
  user: {
    id: number;
    name: string;
    phoneNumber: string;
  };
  orders: Order[];
  totalSpentToday: number;
}

const formatDateToCN = (iso: string) => {
  if (!iso) return '';
  const date = new Date(iso);
  return date.toLocaleString('zh-CN', {
    hour12: false,
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

const stats = reactive<Stats>({
  userCount: 0,
  productCount: 0,
  orderCount: 0,
  totalSales: 0,
});

const loading = ref(false);
const lineChartOption = ref({});
const orders = ref<Order[]>([]);
const lineChart = ref<echarts.ECharts | null>(null);
const categoryTreeChart = ref<echarts.ECharts | null>(null);

const categorySalesData = ref<CategoryTreeNode[]>([]);
const topSpenderData = ref<TopSpenderDto | null>(null);
const productsMap = ref<Record<number,string>>({});

// helper to build tree
type CategoryItem = {
  id: number;
  name: string;
  parentCategoryID: number | null;
};

function buildCategoryTree(sales: CategorySalesFlat[], categories: CategoryItem[]): CategoryTreeNode[] {
  // Step1: build node map
 
  const nodeMap = new Map<number, CategoryTreeNode>();
  categories.forEach(c => nodeMap.set(c.id, { name: c.name, value: 0, children: [] }));

  // Step2: establish parent-child relationships
  categories.forEach(c => {
    if (c.parentCategoryID) {
      const parent = nodeMap.get(c.parentCategoryID);
      const child = nodeMap.get(c.id);
      if (parent && child) (parent.children as CategoryTreeNode[]).push(child);
    }
  });

  // Step3: set leaf sales value
  sales.forEach(s => {
    const node = nodeMap.get(s.categoryId);
    if (node) node.value = s.totalSales;
  });

  // Step4: recursively compute aggregate values
  const aggregate = (node: CategoryTreeNode): number => {
    if (node.children && node.children.length) {
      const childSum = node.children.reduce((sum, child) => sum + aggregate(child), 0);
      node.value += childSum;
    }
    return node.value;
  };

  const roots = categories.filter(c => !c.parentCategoryID).map(c => nodeMap.get(c.id)!);
  roots.forEach(aggregate);
  return roots;
}

// Data processing function
const processOrderDataForChart = (orders: Order[]) => {
    if (!orders || orders.length === 0) {
        return { dates: [], totals: [] };
    }

    const salesByDate: { [key: string]: number } = {};

    orders.forEach(order => {
        const date = formatDateToCN(order.orderDate).split(' ')[0];
        if (!salesByDate[date]) {
            salesByDate[date] = 0;
        }
        salesByDate[date] += order.totalAmount;
    });

    const sortedDates = Object.keys(salesByDate).sort(
        (a, b) => new Date(a).getTime() - new Date(b).getTime()
    );

    const totals = sortedDates.map(date => salesByDate[date]);

    return { dates: sortedDates, totals };
};

const fetchAllData = async () => {
  loading.value = true;
  try {
    const [userRes, productRes, orderRes, categoriesRes, catSalesRes, topSpenderRes] = await Promise.all([
      apiClient.get<any[]>('/user'),
      apiClient.get<any[]>('/product'),
      apiClient.get<Order[]>('/orders'),
      apiClient.get<CategoryItem[]>('/category'),
      apiClient.get<CategorySalesFlat[]>('/product/sales-by-category'),
      apiClient.get('/orders/top-spender-today').catch(err => err.response),
    ]);

    stats.userCount = userRes.data?.length || 0;
    stats.productCount = productRes.data?.length || 0;
    stats.orderCount = orderRes.data?.length || 0;
    stats.totalSales = orderRes.data.reduce((sum: number, order: any) => sum + (order.totalAmount || 0), 0);

    // Process data and set chart options
    const { dates, totals } = processOrderDataForChart(orderRes.data);

    lineChartOption.value = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: dates,
            name: '日期'
        },
        yAxis: {
            type: 'value',
            name: '销售额 (元)'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        series: [
            {
                name: '订单金额',
                type: 'line',
                smooth: true,
                data: totals,
            }
        ]
    };

    const productNameMap: Record<number,string> = {};
    productRes.data.forEach((p:any)=>{productNameMap[p.id]=p.name;});
    productsMap.value = productNameMap;

    categorySalesData.value = buildCategoryTree(catSalesRes.data, categoriesRes.data);
    if(topSpenderRes.status===204){
      topSpenderData.value=null;
    }else{
      topSpenderData.value = topSpenderRes.data as TopSpenderDto;
    }

    // treemap data already assigned

    initCharts();

  } catch (error) {
    console.error("获取仪表盘数据失败:", error);
    ElMessage.error('获取总览数据失败');
  } finally {
    loading.value = false;
  }
};

const initCharts = () => {
    // Tree chart for Category Sales
    const treeEl = document.getElementById('category-tree-chart');
    if (treeEl) {
        categoryTreeChart.value = echarts.init(treeEl);
        const treeOption: echarts.EChartsOption = {
            title: {
                text: '分类销售额层级',
                left: 'center'
            },
            tooltip: {
                trigger: 'item',
                formatter: (info: any) => {
                    return `${info.name}: ¥${info.value.toFixed(1)}`;
                }
            },
            series: [{
                type: 'tree',
                data: categorySalesData.value,
                top: 60,
                bottom: 20,
                layout: 'orthogonal',
                orient: 'TB',
                symbol: 'circle',
                symbolSize: 6,
                initialTreeDepth: -1,
                label: {
                    position: 'top',
                    verticalAlign: 'middle',
                    align: 'center',
                    distance: 5,
                    formatter: (params:any)=> `${params.data.name}\n¥${params.data.value.toFixed(1)}`
                },
                leaves: {
                    label: {
                        position: 'bottom',
                        verticalAlign: 'middle',
                        align: 'center',
                        distance: 5,
                        formatter: (params:any)=> `${params.data.name}\n¥${params.data.value.toFixed(1)}`
                    }
                },
                expandAndCollapse: true,
                animationDuration: 700,
                animationDurationUpdate: 500
            }]
        };
        categoryTreeChart.value.setOption(treeOption);
        window.addEventListener('resize', () => {
            categoryTreeChart.value?.resize();
        });
    }
};

onMounted(async () => {
  fetchAllData();
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.data-card {
  border-radius: 8px;
  overflow: hidden; /* Ensures the background doesn't bleed out */
}

.data-card .el-card__body {
  padding: 0;
  display: flex;
  align-items: center;
}

.card-icon-wrapper {
  font-size: 40px;
  color: #fff;
  padding: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.bg-blue { background-color: #409eff; }
.bg-green { background-color: #67c23a; }
.bg-orange { background-color: #e6a23c; }
.bg-red { background-color: #f56c6c; }


.card-content {
  padding: 20px;
  text-align: center;
  flex-grow: 1;
}

.card-text {
  color: #999;
  font-size: 14px;
  margin-bottom: 10px;
}

.card-num {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.chart {
  height: 400px;
}

.chart-row {
  margin-top: 20px;
}

.top-spender-content {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
